<template>
  <div class="app-container">
    <el-row :gutter="20">
      <leftPanel @leftClick="getTreeNotes" />
      <el-col :span="20" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['juan:juanPaper:random']"
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="juanPaperList.length > 0 ? false : true"
              @click="handleRandom"
              >随机抽卷
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['juan:juanPaper:import']" type="warning" plain icon="el-icon-upload2" size="mini" :disabled="!queryParams.courseId" @click="handleImport('paperBackup')"
              >导入试卷
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['juan:juanPaper:import']" type="warning" plain icon="el-icon-upload2" size="mini" :disabled="!queryParams.courseId" @click="handleImport('paperBackupJson')"
              >导入试卷数据包
            </el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="juanPaperList">
          <el-table-column label="试卷名称" width="120" align="center" prop="paperName" show-overflow-tooltip/>
          <el-table-column label="卷库卷编码" width="120" align="center" prop="newPaperCode" show-overflow-tooltip/>
          <el-table-column label="过程卷编码" width="120" align="center" prop="previousPaperCode" show-overflow-tooltip/>
          <el-table-column label="考试时长" align="center" prop="paperTime"/>
          <el-table-column label="总分" align="center" prop="paperTotalScore" width="80"/>
          <el-table-column label="注意事项" align="center" prop="paperAttention" show-overflow-tooltip/>
          <el-table-column label="难度系数" align="center" prop="paperEasy">
            <template slot-scope="scope">
              {{ scope.row.paperEasy | floatFormat }}
            </template>
          </el-table-column>
          <el-table-column label="院系" align="center" prop="departName" show-overflow-tooltip/>
          <el-table-column label="专业" align="center" prop="majorName" show-overflow-tooltip/>
          <el-table-column label="题库" align="center" prop="courseSubject"/>
          <el-table-column label="创建人" align="center" prop="createdBy"/>
          <el-table-column label="创建时间" align="center" prop="createdTime" width="170">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="150">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-view" v-if="scope.row.paperType == '1'" @click="handleView(scope.row)">查看</el-button>
              <el-button
                v-hasPermi="['juan:juanPaper:remove']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
              <el-button
                v-hasPermi="['juan:juanPaper:analysis']"
                size="mini"
                type="text"
                icon="el-icon-data-analysis"
                @click="handleAnalysis(scope.row)"
              >数据分析
              </el-button>
              <el-button
                v-hasPermi="['juan:juanPaper:export']"
                v-if="scope.row.paperType == '1'"
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleExport(scope.row)"
              >导出EXCEL
              </el-button>
              <el-button
                v-hasPermi="['juan:juanPaper:export']"
                v-if="scope.row.paperType == '1'"
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleExportJson(scope.row)"
                >导出数据包
              </el-button>
              <el-button
                v-hasPermi="['juan:juanPaper:export']"
                v-if="scope.row.paperType == '3'"
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleDownloadPaper(scope.row)"
                >下载试卷
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 试卷导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :multiple="upload.multiple"
        :limit="upload.limit"
        :accept="upload.accept"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :before-upload="handleBeforeUpload"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-change="handleFileChange"
        :auto-upload="false"
        :file-list="fileList"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">
          <div v-if="uploadType === 'paperBackup'">
            <span>1、<span>仅允许导入xls、xlsx、doc、docx格式文件。</span> </span><br>
            <span>2、word文件名称必须跟excel里面的试卷编号保持一致</span>
          </div>
          <span v-if="uploadType === 'paperBackupJson'">仅允许导入json格式文件。</span>
          <!--          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate"-->
          <!--            >下载模板-->
          <!--          </el-link>-->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="requestUpload" v-if="uploadType==='paperBackup'">确 定</el-button>
        <el-button type="primary" @click="submitFileForm" v-if="uploadType==='paperBackupJson'">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 随机抽卷对话框 -->
    <el-dialog :title="'随机抽卷'" :visible.sync="randomOpen" width="55%" append-to-body :before-close="randomClose" class="common-dialog">
      <Random v-if="randomOpen" :course-id="queryParams.courseId" @close="randomClose"></Random>
    </el-dialog>
  </div>
</template>

<script>
  import Random from "./random.vue";
  import { deljuanPaperBakeup, queryBakeupList, uploadPaperBackup, uploadPaperBackupJson } from '@/api/juan/juanPaper'
  import { getToken } from "@/utils/auth";
  import request from "@/utils/request";

  export default {
    name: 'PaperBakeup',
    components: { Random },
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 试卷表格数据
        juanPaperList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        randomOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          courseId: undefined,
          paperCode: undefined,
          paperName: undefined,
          paperType: undefined,
          paperSubject: undefined,
          paperDes: undefined,
          paperStatus: undefined,
          paperEndTime: undefined,
          createdBy: undefined,
          createdTime: undefined,
          updatedBy: undefined,
          updatedTime: undefined,
          userName: undefined,
          departName: undefined,
          majorName: undefined,
          courseSubject: undefined,
          paperEasy: undefined
        },
        randomOpen: false,
        // 试卷导入参数
        upload: {
          // 是否显示弹出层（试卷导入）
          open: false,
          // 弹出层标题（试卷导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          //url: "http://127.0.0.1:8075/juan/juanPaperBakeup/importPaperBackupJson",
          url: "",
          multiple: false,
          limit: 1,
          accept: ".xlsx, .xls,.doc,.docx"
        },
        uploadList: [],
        fileList: [],
        url: "http://127.0.0.1:8075/juan/juanPaperBakeup/importData",
        jsonUrl: "http://127.0.0.1:8075/juan/juanPaperBakeup/importPaperBackupJson",
        uploadType: 'paperBackup',
      }
    },
    methods: {
      // 树节点单击事件
      getTreeNotes(obj) {
        //console.log('getTreeNotes', JSON.parse(JSON.stringify(obj)))
        if (obj) {
          this.queryParams.courseId = obj.treeNode.id;
          this.handleQuery();
        }else {
          this.queryParams.courseId = undefined;
          this.juanPaperList = [];
        }
      },
      /** 查询试卷列表 */
      getList() {
        this.loading = true
        // this.queryParams.paperId = this.paperId
        queryBakeupList(this.queryParams)
          .then((response) => {
            this.juanPaperList = response.rows
            this.total = response.total
            this.loading = false
          })
          .catch(() => {
            this.loading = false
          })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          paperId: undefined,
          courseId: undefined,
          paperCode: undefined,
          paperName: undefined,
          paperType: undefined,
          paperSubject: undefined,
          paperDes: undefined,
          paperStatus: '0',
          paperEndTime: undefined,
          paperAttention: undefined,
          paperSealLine: undefined,
          paperTotalScore: undefined,
          paperTime: undefined,
          createdBy: undefined,
          createdTime: undefined,
          updatedBy: undefined,
          updatedTime: undefined
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      /** 查看按钮操作 */
      handleView(row) {
        this.$router.push({
          path: '/juanPaper/juanPaper/historyView',
          query: {
            paperId: row.id,
            page: 'view'
          }
        })
      },
      /** 数据分析按钮操作 */
      handleAnalysis(row) {
        this.$router.push({
          path: '/juanPaper/juanPaper/analysis',
          query: {
            // paperId: row.paperId,
            paperId: row.id,
            type: 'history'
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const paperIds = row.id || this.ids
        this.$modal
          .confirm('是否确认删除试卷？')
          .then(() => {
            this.loading = true
            return deljuanPaperBakeup(paperIds)
          })
          .then(() => {
            this.loading = false
            this.getList()
            this.$modal.msgSuccess('删除成功')
          })
          .catch(() => {
          })
          .finally(() => {
            this.loading = false
          })
      },
      /** 导出按钮操作 */
      handleExport(data) {
        this.download('juan/juanPaperBakeup/exportData/' + data.id, {}, data.paperName + `.xlsx`)
      },
      /** 导出数据包按钮操作 */
      handleExportJson(data) {
        request({
          url: 'juan/juanPaperBakeup/exportPaperBackupJson/' + data.id,
          method: 'post'
        }).then((res) => {
          this.saveJSON(res, data.paperName + `juanPaper.json`)
        })
      },
      saveJSON(data, filename) {
        if (!data) {
          return;
        }
        if (!filename) {
          filename = "json.json";
        }
        if (typeof data === "object") {
          data = JSON.stringify(data, undefined, 4);
        }
        let blob = new Blob([data], { type: "text/json" });
        let e = document.createEvent("MouseEvents");
        let a = document.createElement("a");
        a.download = filename;
        a.href = window.URL.createObjectURL(blob);
        a.dataset.downloadurl = ["text/json", a.download, a.href].join(":");
        e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        a.dispatchEvent(e);
      },
      // 下载试卷
      handleDownloadPaper(data) {
        this.download("juan/juanPaperBakeup/downloadPaper/" + data.id, {}, data.paperName + `.docx`);
      },
      // 随机抽卷
      handleRandom() {
        this.randomOpen = false;
        this.$nextTick(() => {
          this.randomOpen = true;
        });
        localStorage.removeItem("selection");
      },
      //关闭抽卷弹窗
      randomClose() {
        this.randomOpen = false;
        localStorage.removeItem("selection");
      },

      /** 导入试卷按钮操作 */
      handleImport(type) {
        this.fileList = [];
        if(type === "paperBackup"){
            this.upload.title = "试卷导入";
            this.upload.url = '#';
            this.uploadType = type;
            this.upload.multiple = true;
            this.upload.limit = 2;
            this.upload.accept = ".xlsx, .xls,.doc,.docx"
        }
        if(type === "paperBackupJson"){
            this.upload.title = "试卷数据包导入";
            this.upload.url = this.jsonUrl;
            this.uploadType = type;
            this.upload.multiple = false;
            this.upload.limit = 1;
            this.upload.accept = ".json"
        }
        this.upload.open = true;
      },
      // 项目附件上传前判断大小并添加
      handleBeforeUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 5
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 5MB!')
          return isLt2M
        } else {
          // 符合条件就直接上传
        }
      },
      handleFileChange(file, fileList) {
        this.fileList = fileList;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download("juan/juanPaper/importTemplate", {}, `试卷导入模板.xlsx`);
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      requestUpload() {
        let formData = new FormData(); //  用FormData存放上传文件
        this.fileList.forEach((val,index) => {
          var s2 = val.name.substring(val.name.lastIndexOf("."));
          var str1 = '.xlsx, .xls';
          var str2 = '.doc,.docx';
          if(str1.indexOf(s2) !=-1){
            formData.append("excelFile",val.raw)
          }
          if(str2.indexOf(s2) !=-1){
            formData.append("wordFile",val.raw)
          }
        });
        formData.append("courseId",this.queryParams.courseId);
        //console.log(formData.get('wordFile'))

        request({
          url: this.url,
          method: 'post',
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          data: formData,
        }).then((res) => {
          console.log(res,'调用成功')
          this.handleFileSuccess(res)
        })
      },
    },
  }
</script>
<style lang="scss" scoped>
</style>
